#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>

void change_sh2(int argc, char *argv[]) {
	int aim = argc - 1;
	char *temp = malloc(strlen(argv[aim]));
	strcpy(temp,argv[aim]);

	if(argv[aim] != NULL && argv[aim][0] == '>') {
		if(argv[aim][1] == '>') {
			int fd = open(strtok(temp,">>") , O_WRONLY | O_APPEND | O_CREAT , 0666);
			dup2(fd,1);
			close(fd);
			argv[aim] = NULL;
		}
		else {
			int fd = open(strtok(temp,">") , O_WRONLY | O_TRUNC | O_CREAT , 0666);
			dup2(fd,1);
			close(fd);
			argv[aim] = NULL;
		}
	}
	if(argv[aim] !=NULL && argv[aim][0] == '<') {
		int fd = open(strtok(temp,"<") , O_RDONLY);
		dup2(fd,0);
		close(fd);
		argv[aim] = NULL;
	}
}

int main() {
	while(1) {
		char line[128];
		printf("> ");
		fflush(stdout);
		fgets(line,sizeof(line),stdin);
		line[strlen(line)-1] = '\0';
		
		char *argv[16] = {NULL};
		int i = 0;
		char *word = strtok(line," ");
		while(word != NULL) {
			argv[i] = (char *)malloc(strlen(word));
			strcpy(argv[i],word);
			word = strtok(NULL," ");
			i+=1;
		}
		argv[i] = NULL;

		pid_t pid = fork();
		int a = strcmp(argv[0],"cd");
		int b = strcmp(argv[0],"pwd");
		int c = strcmp(argv[0],"exit");

		if(argv[0] == NULL) {
			return 0;
		}
		if(pid < 0) {
			return -1;
		}
		else if(pid == 0) {
			change_sh2(i,argv);
			if(a != 0 && b != 0 && c != 0) {
				int error = execvp(argv[0],argv);
				return 127;
			}
			return 0;
		}
		else {
			int status;
			wait(&status);
			if(!(WIFEXITED(status))) return -1;
			if(a == 0) {
				chdir(argv[1]);
				continue;
			}
			if(b == 0) {
				char path[128];
				getcwd(path,sizeof(path));
				printf("%s\n",path);
				continue;
			}
			if(c == 0) return 0;
		}
	}
	return 0;
}
